// Copyright (c) 2025 Shenzhen Kaihong Digital Industry Development Co., Ltd.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::collections::{btree_map, BTreeMap};

use serde::{Deserialize, Serialize};

use crate::VersionReq;

#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RequirementsConfig(pub BTreeMap<String, VersionReq>);

impl RequirementsConfig {
    pub fn new() -> Self {
        Self(BTreeMap::new())
    }

    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    pub fn contains(&self, name: &String) -> bool {
        self.0.contains_key(name)
    }

    pub fn iter(&self) -> btree_map::Iter<'_, String, VersionReq> {
        self.0.iter()
    }
}

impl FromIterator<(String, VersionReq)> for RequirementsConfig {
    fn from_iter<T: IntoIterator<Item = (String, VersionReq)>>(iter: T) -> Self {
        Self(BTreeMap::from_iter(iter))
    }
}

#[cfg(test)]
mod test {
    use crate::{config::RequirementsConfig, Version, VersionOp, VersionReq};

    #[test]
    fn test_requirements_config_serialize() {
        let config = RequirementsConfig([
            (
                "pkg1".to_string(),
                VersionReq::all(),
            ),
            (
                "pkg2".to_string(),
                VersionReq::new(VersionOp::Greater, Version::from_major(1)),
            )
        ].into_iter().collect());

        assert_eq!(
            toml::to_string(&config).unwrap(),
            "pkg1 = \"*\"\n\
             pkg2 = \">1\"\n".to_string()
        );
    }

    #[test]
    fn test_requirements_config_deserialize() {
        let config = RequirementsConfig([
            (
                "pkg1".to_string(),
                VersionReq::all(),
            ),
            (
                "pkg2".to_string(),
                VersionReq::new(VersionOp::Greater, Version::from_major(1)),
            )
        ].into_iter().collect());
        assert_eq!(
            toml::from_str("\
                pkg1 = \"*\"\n\
                pkg2 = \">1\"\n"
            ),
            Ok(config)
        )
    }
}